package com.xiangzi.xzschedule.quartz.spring;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xiangzi.xzschedule.job.PrintTimeJob;

public class ScheduleWidthDatasource {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				new String[] { "classpath*:META-INF/spring/spring.xml",
						"classpath*:META-INF/spring/spring-quartz-datasources.xml" });
		System.out.println(applicationContext);
		System.out.println(SpringUtil.getApplicationContext());

		String jobGroup = "defaultJobGroup";
		Scheduler scheduler = applicationContext.getBean(Scheduler.class);

		String jobName = "PrintTimeJob";

		scheduleJob(jobGroup, jobName, scheduler);

		sleep(60 * 1000);

		pauseJob(jobGroup, jobName, scheduler);
		
		sleep(10 * 1000);
		
		resumeJob(jobGroup, jobName, scheduler);
		
		sleep(30 * 1000);
		
		deleteJob(jobGroup, jobName, scheduler);
		
	}

	public static void resumeJob(String jobGroup, String jobName,
			Scheduler scheduler) {
		try {
			JobKey jobKey = new JobKey(jobName, jobGroup);
			scheduler.resumeJob(jobKey);
			System.out.println("恢复任务 ---> " + jobKey.toString());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	public static void deleteJob(String jobGroup, String jobName,
			Scheduler scheduler) {
		try {
			JobKey jobKey = new JobKey(jobName, jobGroup);
			scheduler.deleteJob(jobKey);
			System.out.println("删除任务 ---> " + jobKey.toString());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	public static void pauseJob(String jobGroup, String jobName,
			Scheduler scheduler) {
		try {
			JobKey jobKey = new JobKey(jobName, jobGroup);
			scheduler.pauseJob(jobKey);
			System.out.println("暂停任务 ---> " + jobKey.toString());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	public static void scheduleJob(String jobGroup, String jobName,
			Scheduler scheduler) {
		JobDetail jobDetail = JobBuilder.newJob(PrintTimeJob.class)
				.withIdentity(jobName, jobGroup).build();
		jobDetail.getJobDataMap().put("tId", "tId001");
		CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder
				.cronSchedule("0/2 * * * * ?");
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity(jobName, jobGroup)
				.withSchedule(cronScheduleBuilder).build();
		try {
			scheduler.scheduleJob(jobDetail, trigger);
			System.out.println("添加任务 ---> " + jobDetail.getKey().toString());
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	private static void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
